package cn.micai.queue;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @ClassName Preloader
 * @Description 使用FutureTask预载稍后需要的数据
 * @Author zhaoxinguo
 * @Date 2018/7/7 16:09
 * @Version 1.0
 **/
public class Preloader {

    private final FutureTask<ProductInfo> future = new FutureTask<ProductInfo>(new Callable<ProductInfo>() {
        @Override
        public ProductInfo call() throws Exception {
            // 从数据库加载商品数据
            return loadProductInfo();
        }
    });

    private final Thread thread = new Thread(future);

    private void start() {
        thread.start();
    }

    public ProductInfo get() throws ExecutionException, InterruptedException, DataLoadException {
        /*try {
            return future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;*/
        try {
            return future.get();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof DataLoadException)
                throw (DataLoadException) cause;
            else
                throw launderThrowable(cause);
        }
    }

    public static RuntimeException launderThrowable(Throwable t) {
        if (t instanceof RuntimeException)
            return (RuntimeException) t;
        else if (t instanceof Error)
            throw (Error) t;
        else
            throw new IllegalArgumentException("Not unchecked", t);
    }

    private ProductInfo loadProductInfo() {
        return new ProductInfo();
    }

}
